package org.shop.controller.autotrophy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Goods;
import org.shop.entity.SupplierGoods;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.GoodsService;
import org.shop.service.SupplierGoodsService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.coobird.thumbnailator.Thumbnails;

@Controller
@RequestMapping("autotrophy")
public class AutotrophyGoodsController {
	
	private static Logger logger = LogManager.getLogger(AutotrophyGoodsController.class);


	@Autowired
	private SupplierGoodsService supplierGoodsService;
    @Autowired
    private GoodsService goodsService;
    
	/**
     * 获取供应商商品列表
     * @param req
     * @return
     */
    @RequestMapping("/getSupplierGoodsList")
    @ResponseBody
    public Map<String, Object> getShopGoodsList(HttpServletRequest req){
        Map<String, Object> map = new HashMap<String, Object>();
        String currentPage = req.getParameter("offset");
        String pageSize = req.getParameter("limit");
        String goodsName = req.getParameter("goodsName");
        String selectType = req.getParameter("selectType");
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", Integer.parseInt(currentPage));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("supplierGoodsName", goodsName);
            paramMap.put("selectType", selectType);
            map = supplierGoodsService.getSupplierGoodsList(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return map;
    }
    
    /**
     * 通过供应商品ID获取商品信息
     * @param req
     * @return
     */
    @RequestMapping("/getSupplierGoodsInfo")
    @ResponseBody
    public SupplierGoods getSupplierGoodsInfo(HttpServletRequest req){
        String supplierGoodsId = req.getParameter("supplierGoodsId");
        SupplierGoods supplierGoods = null;
        try {
        	supplierGoods = supplierGoodsService.selectByPrimaryKey(Long.parseLong(supplierGoodsId));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return supplierGoods;
    }
    /**
     * 通过商品ID获取商品信息
     * @param req
     * @return
     */
    @RequestMapping("/getGoodsInfo")
    @ResponseBody
    public Goods getGoodsInfo(HttpServletRequest req){
        String goodsId = req.getParameter("goodsId");
        Goods goodsInfo = null;
        try {
            goodsInfo = goodsService.selectByPrimaryKey(Long.parseLong(goodsId));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return goodsInfo;
    }
    
    /**
     * 发布自营商品（自营）
     * @param req
     * @return
     */
    @RequestMapping("/addAutotrophyGoods")
    @ResponseBody
    public Map<String, Object> addGoods(HttpServletRequest req){
        Map<String, Object> map=new HashMap<String, Object>();
        String photoStr="";
        String mainPhotoStr="";
        FTPClient ftpClient =null;
        InputStream is = null;
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
        //转换成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;

        String supplierGoodsId = multiRequest.getParameter("supplierGoodsId");
        String goodsName = multiRequest.getParameter("goodsName");
        String classifyId1 = multiRequest.getParameter("classifyId1");
        String goodsStock = multiRequest.getParameter("addGoodsStock");
        String googsWeight = multiRequest.getParameter("googsWeight");
        String goodsSize = multiRequest.getParameter("goodsSize");
        String goodsPrice = multiRequest.getParameter("goodsPrice");
        String goodsIntro = multiRequest.getParameter("goodsIntro");
        String str=goodsName+goodsSize+goodsIntro;
        String textBlackList=CommonUtil.getPropertiesParam("textBlackList");
        try{
          
            for(String textBlack:textBlackList.split(",")){
                if(str.contains(textBlack)){
                    map.put("state", 2);
                    map.put("msg", "文字不合法");
                    return map;
                }
            }
            String goodsMainText = multiRequest.getParameter("goodsMainText");
            String[] goodsTexts = multiRequest.getParameterValues("goodsText");
            mainPhotoStr=goodsMainText;
            for(String goodsText:goodsTexts){
                if(!StringUtils.isEmpty(goodsText)){
                    if(StringUtils.isEmpty(photoStr)){
                        photoStr=goodsText;
                    }else{
                        photoStr+=","+goodsText;
                    }
                }
            }
            //判断 request 是否有文件上传,即多部分请求
            if(multipartResolver.isMultipart(req)){
                //取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                //创建ftp链接
                String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
                ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
                while(iter.hasNext()){
                    String name=iter.next();
                    if(name.equals("goodsMainPhoto")){
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        is=file.getInputStream();
                                        ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                        //按照比例进行缩小和放大
                                        Thumbnails.of(file.getInputStream()).size(120,120).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
                                    }
                                }
                            }
                        }
                    }else{
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                    	 myFileName=FtpUtil2.generateFileName(myFileName);
                                         //按照比例进行缩小和放大
                                         is=file.getInputStream();
                                         int len=is.available();
                                         ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                         if(len/1024>600) {//kb
                                         	//按照比例进行缩小和放大
                                             Thumbnails.of(is).scale(0.2f).toOutputStream(bos);
                                             is = new ByteArrayInputStream(bos.toByteArray());
                                         }
                                        
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        if("".equals(photoStr)){
                                            photoStr+=ftp_photoDirectory+"/"+myFileName;
                                        }else{
                                            photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                Goods goods = new Goods();
                goods.setSupplierGoodsId(Long.parseLong(supplierGoodsId));
                goods.setGoodsName(goodsName);
                goods.setGoodsImage(photoStr);
                goods.setGoodsThums(mainPhotoStr);
                goods.setGoodsPrice(new BigDecimal(goodsPrice));
                goods.setClassifyId1(Long.parseLong(classifyId1));
                if(ObjectUtils.isEmpty(goodsStock)) {
                }else {
                	goods.setGoodsStock(Integer.parseInt(goodsStock));
                }
                goods.setGoogsWeight(googsWeight);
                goods.setGoodsSize(goodsSize);
                goods.setCreateDate(new Date());
                goods.setGoodsIntro(goodsIntro);
                goods.setMerchantId(ud.getMerchantId());
                goods.setUserId(ud.getUserId());
                goods.setState((byte)2);
                goods.setGoodsIdentifying((byte) 4);
                goodsService.insertSelective(goods);
                map.put("state", 1);
                map.put("msg", "发布成功");
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
            map.put("msg", "发布失败");
        }finally {
        	try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
        }
        return map;
    }
    
    /**
     * 根据商品id跳转到自营商品详细信息
     * @param req
     * @return
     */
    @RequestMapping("/getAutotrophyGoodsInfo")
    public String getAutotrophyGoodsInfo(HttpServletRequest req){
        try{
            Long goodsId = Long.parseLong(req.getParameter("goodsId"));
            Goods goods = goodsService.selectByPrimaryKey(goodsId);
            req.setAttribute("goods", goods);
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return "autotrophy/goodsInfo";
    }
    
    /**
     * 自营进行下架自营商品
     * @param req
     * @return
     */
    @RequestMapping("/closeGoods")
    @ResponseBody
    public Map<String,Object> closeGoods(HttpServletRequest req){
    	Map<String,Object> map = new HashMap<String,Object>();
    	Long goodsId = Long.parseLong(req.getParameter("goodsId"));
    	try {
    		Goods goods = new Goods();
    		goods.setGoodsId(goodsId);
    		goods.setState((byte) 5);
			int num = goodsService.updateByPrimaryKeySelective(goods );
			map.put("state", num);
    	}catch(Exception e) {
    		e.printStackTrace();
    		map.put("state", 0);
    		logger.error(e.getMessage());
    	}
    	return map;
    }
	
    /**
     * 商品修改
     * @param req
     * @return
     */
    @RequestMapping("/openGoods")
    @ResponseBody
    public Map<String, Object> openGoods(HttpServletRequest req){
        Map<String, Object> map=new HashMap<String, Object>();
        String photoStr="";
        String mainPhotoStr="";
        FTPClient ftpClient =null;
        InputStream is = null;
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
        //转换成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
        Long supplierGoodsId = Long.parseLong(multiRequest.getParameter("supplierGoodsId"));
        String goodsName = multiRequest.getParameter("goodsName");
        String classifyId1 = multiRequest.getParameter("classifyId1");
        String goodsStock = multiRequest.getParameter("goodsStock");
        String googsWeight = multiRequest.getParameter("googsWeight");
        String goodsSize = multiRequest.getParameter("goodsSize");
        String goodsPrice = multiRequest.getParameter("goodsPrice");
        String goodsIntro = multiRequest.getParameter("goodsIntro");
        String goodsId = multiRequest.getParameter("goodsId");

        String goodsMainText = multiRequest.getParameter("goodsMainText");
        String[] goodsTexts = multiRequest.getParameterValues("goodsText");
        try{
            mainPhotoStr=goodsMainText;
            for(String goodsText:goodsTexts){
                if(!StringUtils.isEmpty(goodsText)){
                    if(StringUtils.isEmpty(photoStr)){
                        photoStr=goodsText;
                    }else{
                        photoStr+=","+goodsText;
                    }
                }
            }

            String str=goodsName+goodsSize+goodsIntro;
            String textBlackList=CommonUtil.getPropertiesParam("textBlackList");
            for(String textBlack:textBlackList.split(",")){
                if(str.contains(textBlack)){
                    map.put("state", 2);
                    map.put("msg", "文字不合法");
                    return map;
                }
            }
            //判断 request 是否有文件上传,即多部分请求
            if(multipartResolver.isMultipart(req)){
                //取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                //创建ftp链接
                String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
                ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
                while(iter.hasNext()){
                    String name=iter.next();
                    if(name.equals("goodsMainPhoto")){
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        is=file.getInputStream();
                                        ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                        //按照比例进行缩小和放大
                                        Thumbnails.of(file.getInputStream()).size(120,120).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
                                    }
                                }
                            }
                        }
                    }else{
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                    	 myFileName=FtpUtil2.generateFileName(myFileName);
                                         //按照比例进行缩小和放大
                                         is=file.getInputStream();
                                         int len=is.available();
                                         ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                         if(len/1024>600) {//kb
                                         	//按照比例进行缩小和放大
                                             Thumbnails.of(is).scale(0.2f).toOutputStream(bos);
                                             is = new ByteArrayInputStream(bos.toByteArray());
                                         }
                                        
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        if("".equals(photoStr)){
                                            photoStr+=ftp_photoDirectory+"/"+myFileName;
                                        }else{
                                            photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                Goods goods = new Goods();
                goods.setGoodsId(Long.parseLong(goodsId));
                goods.setGoodsName(goodsName);
                goods.setGoodsImage(photoStr);
                goods.setGoodsThums(mainPhotoStr);
                goods.setGoodsPrice(new BigDecimal(goodsPrice));
                goods.setClassifyId1(Long.parseLong(classifyId1));
                goods.setGoodsStock(Integer.parseInt(goodsStock));
                goods.setGoogsWeight(googsWeight);
                goods.setGoodsSize(goodsSize);
                goods.setCreateDate(new Date());
                goods.setGoodsIntro(goodsIntro);
                goods.setMerchantId(ud.getMerchantId());
                goods.setState((byte) 2);
                goodsService.updateByPrimaryKeySelective(goods);
                SupplierGoods sd = new SupplierGoods();
                sd.setSupplierGoodsId(supplierGoodsId);
                sd.setSupplierGoodsStock(Integer.parseInt(goodsStock));
				supplierGoodsService.updateByPrimaryKeySelective(sd );
                map.put("state", 1);
                map.put("msg", "发布成功");
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
            map.put("msg", "发布失败");
        }finally {
         	try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
        }
        return map;
    }
    
    
}
